package initialize

import (
	"context"
	"fmt"
	"github.com/olivere/elastic/v7"
	"go.uber.org/zap"
	"log"
	"os"
	"service/goods_srv/global"
	"service/goods_srv/model"
	"time"
)

func InitEs() {
	host := fmt.Sprintf("http://%s:%d", global.ServerConfig.EsInfo.Host, global.ServerConfig.EsInfo.Port)
	logger := log.New(os.Stdout, "ygshop", log.LstdFlags)
	options := []elastic.ClientOptionFunc{
		elastic.SetURL(host),
		elastic.SetSniff(false),                          //是否开启集群嗅探
		elastic.SetHealthcheckInterval(10 * time.Second), //设置两次运行状况检查之间的间隔, 默认60s
		elastic.SetGzip(false),                           //启用或禁用gzip压缩
		elastic.SetTraceLog(logger),                      // 显示请求es的详细信息
		//elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC ", log.LstdFlags)),  //ERROR日志输出配置
		//elastic.SetInfoLog(log.New(os.Stdout, "", log.LstdFlags)),  //INFO级别日志输出配置
	}
	//options = append(options, elastic.SetBasicAuth(
	//	"xxxx",            //账号
	//	"xxxxxxxxxxxxxx",  //密码
	//))
	var err error
	global.EsClient, err = elastic.NewClient(options...)
	if err != nil {
		panic(err)
	}

	// 新建mapping和index
	exists, err := global.EsClient.
		IndexExists(model.EsGoods{}.GetIndexName()).
		Do(context.Background())
	if err != nil {
		panic(err)
	}
	if !exists {
		_, err = global.EsClient.
			CreateIndex(model.EsGoods{}.GetIndexName()).
			BodyString(model.EsGoods{}.GetMapping()).
			Do(context.Background())
		if err != nil {
			panic(err)
		}
		zap.S().Debugf("es索引%s及其mapping已创建成功", model.EsGoods{}.GetIndexName())
	}
}
